<template>
  <div >

        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <date-range-picker
                v-model="query.queryDate"
                valueFormat="yyyy-MM-dd"
                class="date-item"
                @keyup.enter.native="crud.toQuery" @input="$forceUpdate()"/>
            <rrOperation />
            <el-button type="primary" style="margin-bottom: 10px; vertical-align: middle;" size="mini" icon="el-icon-download" @click="downloadExcel">导出</el-button>
          </div>
          <crudOperation />
        </div>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading"  :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
          <!--      <el-table-column prop="dealer_name" label="所属单位" width="200" />-->
          <el-table-column prop="created_at"  label="作业开始时间" width="150"  />
          <el-table-column prop="workname" label="作业名" width="120" align="center"/>
          <el-table-column prop="type" label="作业类型" width="100" align="center"/>
          <el-table-column prop="crop" label="作物类型" width="100" align="center"/>
          <el-table-column prop="area" label="作业面积(亩)" width="100" align="center"/>
          <el-table-column prop="duration" label="作业时长(H)" width="100" align="center"/>
          <el-table-column prop="mileage" label="作业里程(KM)" width="100" align="center"/>
          <el-table-column prop="farmer" label="作业用户" width="100" align="center"/>
          <el-table-column prop="width" label="作业幅宽" width="100" align="center"/>
          <el-table-column prop="province" label="所在省" width="100" align="center"/>
          <el-table-column prop="city" label="所在市" width="100" align="center"/>
          <el-table-column prop="district" label="所在区县" width="100" align="center"/>
          <el-table-column prop="start_lon" label="开始经度" width="100" align="center"/>
          <el-table-column prop="start_lat" label="开始纬度" width="100" align="center"/>
          <el-table-column prop="end_lon" label="结束经度" width="100" align="center"/>
          <el-table-column prop="end_lat" label="结束纬度" width="100" align="center"/>
        </el-table>
        <!--分页组件-->
        <pagination />

  </div>
</template>

<script>

import CRUD, { crud, form, header, presenter } from '@crud/V2/crud'
import crudOperation from '@crud/V2/CRUD.operation'
import pagination from '@crud/V2/Pagination'
import rrOperation from '@crud/V2/RR.operation'
import DateRangePicker from '@/components/DateRangePicker'


import { getWorkareaDateList } from '@/api/jf/eqBiz'

export default {
  name: 'workAreaLianshi',
  components: { pagination, crudOperation, rrOperation,DateRangePicker },
  cruds() {
    return CRUD({ url: 'api/v2/biz/eq/getWorkAreaLianshi' })

  },
  mixins: [presenter(), header()],
  dictsV2: ['farms'],
  props: {
    badgeDate: ['2023-03-01', '2023-03-11', '2023-03-15'],
    pickerOptions: {
      cellClassName: (time) => {
        if (_this.badgeDate.includes(_this.parseTime(time, '{y}-{m}-{d}'))) {
          return 'badge'
        }
      }
    },
    eqObj: {
      type: Object,
      default:function(){
        return {}
      }
    }
  },
  data() {
    const _this = this
    return {
      syncLoading: false,
      eqCode: ""
    }
  },
  watch: {
    'eqObj': {
      handler(newVal, oldVal) {
        const today = new Date(newVal.rcv_time);
        const yesterday = new Date(today.getTime() - 1000*60*60*24*7);
        this.query.queryDate = [this.dateFormat("YYYY-mm-dd",yesterday),this.dateFormat("YYYY-mm-dd",today)]
        this.query.eqCode = this.$route.params.eqCode
        this.crud.toQuery()
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.crud.optShow = { add: false, edit: false, del: false, download: false }
    this.eqCode = this.$route.params.eqCode
    //初始化日期标记
    getWorkareaDateList({eqCode:this.eqCode}).then(data => {
      this.badgeDate = [];
      const _this = this
      if(data.data && data.data.length > 0){
        data.data.forEach(function(obj){
          _this.badgeDate.push(obj.date)
        })
        console.log("this.badgeDate",this.badgeDate)
      }
    })
    //初始化查询时间
    // const today = new Date();
    // const yesterday = new Date(today.getTime() - 1000*60*60*24*7);
    // // console.log(today.getDate())
    // // console.log(yesterday.getDay())
    // this.query.queryDate = [this.dateFormat("YYYY-mm-dd",yesterday),this.dateFormat("YYYY-mm-dd",today)]
    // this.query.eqCode = this.$route.params.eqCode
    // this.crud.toQuery()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      console.log(this.query)
      if(this.query.queryDate) {
        this.query.start_ts = new Date(this.query.queryDate[0] + " 00:00:00").getTime()
        this.query.end_ts = new Date(this.query.queryDate[1] + " 23:59:59").getTime()
        return true
      }
      return false
    },
    changeTime(e){
      this.$forceUpdate()
      // this.query.queryTime1 = e
    },

    // 入参 fmt-格式 date-日期
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
      };
      return fmt;
    },
    parseTime(time, cFormat) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string')) {
          if ((/^[0-9]+$/.test(time))) {
            time = parseInt(time)
          } else {
            time = time.replace(new RegExp(/-/gm), '/')
          }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
        return value.toString().padStart(2, '0')
      })
      return time_str
    },
    downloadExcel(){
      this.crud.doExport()
    }
  }
}
</script>

<style scoped>

</style>
<style>
.picker-popper .el-date-table .badge::after {
  position: absolute;
  content: "";
  right: 4px;
  top: 4px;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: red;
}
</style>
